import Vue from "vue";
import default_pic from "@/assets/images/Rectangle.png";
import error_pic from '@/assets/images/error.png';
import loading_pic from '@/assets/images/loading.png';
import avatar from '@/assets/images/touxiang.jpeg';
import _ from "lodash";

const getImageData = (src, onSuccess, onError) => {
    let imgDom = document.createElement('img');
    imgDom.onload = onSuccess;
    imgDom.onerror = onError;
    imgDom.src = src;
}

// 获取图片url
const getSrc = (el, {value, oldValue, modifiers = {}} = {}) => {
    let src = "";

    let bindSrc = _.get(value, 'src') || value;

    src = bindSrc;

    if(!src || src === 'undefined') {
        // 如果没有绑定值，那就从标签的正常属性拿
        let isImg = el.tagName === 'IMG';

        if(isImg) {
            src = el.src;
        }else {
            let str = el.style.backgroundImage || el.style.background;
            let match = str && str.match(/(?<=url\(['|"])[\d|\D]+(?=['|"]\))/);
            src = match && match[0];
        }
    }

    return src;
}
// 设置图片url
const setSrc = (el, url) => {
    let isImg = el.tagName === 'IMG';
    if(isImg) {
        el.src = url;
    }else {
        el.style.backgroundImage = `url("${url}")`;
    }
}
// 绑定点击查看大图事件
const clickHandle = (e) => {
    let src = e.target.dataset.src;
    let instance = window.g_instance;
    instance&&instance.$store.commit("global/OPEN_IMAGE", {
        src: src,
    });
    return e.stopPropagation();
}
const attachOpenDetail = (el) => {
    el.removeEventListener('click', clickHandle);
    el.addEventListener('click', clickHandle);
}

/**
 * @desc 加载图片，展示loading状态，失败，无图片默认占位符。
 * @modifiers {isAvatar} 圆形头像修饰符
 * @modifiers {openDetail} 点击图片弹出大图预览修饰符
 * @value {string | object} 绑定值。绑定值为src的字符串或者带src的对象
 * 
 * @returns 
 */
const loadingImage = (el, {name, value,oldValue, modifiers}, vnode, oldVnode) => {
    let isImg = el.tagName === 'IMG';
    let newSrc = _.get(value, "src") || value;
    let oldSrc = _.get(oldValue, "src") || oldValue;

    if((oldSrc === newSrc) && newSrc) {
        return;
    }

    let imageMap = {
        default_pic: _.get(value, "default") || default_pic,
        error_pic: _.get(value, "error") || error_pic,
        loading_pic,
    }

    let isAvatar = modifiers.isAvatar;

    if(isAvatar) {
        imageMap.default_pic = _.get(value, "default") || _.get(value, "avatar") || avatar;
        imageMap.error_pic = imageMap.default_pic;
    }

    let src = getSrc(el, {
        value, oldValue, modifiers
    });
    if(src === el.getAttribute('data-src')) {
        return;
    }

    // 先展示loading状态，图片加载成功后展示图片，或者失败或者默认状态
    setSrc(el, imageMap.loading_pic);
    if(isImg) {

        if(!src) {
            setSrc(el, imageMap.default_pic);
            return;
        }

        getImageData(src, () => {
            setSrc(el, src);
            modifiers.openDetail && attachOpenDetail(el);
        }, () => {
            setSrc(el, imageMap.error_pic);
        })
    }else {
        let hasContain = [...(el.classList || [])].includes("back_img_contain");

        el.classList.add('back_img_contain');

        if(!src || src === "undefined") {
            setSrc(el, imageMap.default_pic);
            return;
        }
        getImageData(src, () => {
            setSrc(el, src);
            modifiers.openDetail && attachOpenDetail(el);
            if(!hasContain) {
                el.classList.remove('back_img_contain');
            }
        }, () => {
            setSrc(el, imageMap.error_pic);
        })

    }
    el.setAttribute('data-src', src || "");
}

// 图片加载中和加载失败的默认展示展位图的指令
Vue.directive("load-image", {
    bind: loadingImage,
    inserted: function() {},
    update: loadingImage,
    componentUpdated: function() {},
    unbind: function() {}
});
